package Libs.Componentes.Visuais
{
    import flash.events.Event;
    import flash.events.MouseEvent;
    import flash.events.ProgressEvent;
    import flash.events.TimerEvent;
    import flash.net.FileReference;
    import flash.net.URLRequest;
    import flash.net.URLRequestMethod;
    import flash.utils.Timer;
    
    import mx.containers.TitleWindow;
    import mx.controls.Button;
    import mx.controls.ProgressBar;
    import mx.core.Application;
    import mx.managers.PopUpManager;
    import mx.messaging.config.ServerConfig;

    public class UploadButton extends Button
    {
        /**
        * Define qual o arquivo .NET será chamado para realizar o upload físico do arquivo
        */
        private var UPLOAD_URL:String;
	
        private var fr:FileReference;
        private var pb:ProgressBar = new ProgressBar();
        private var tw:TitleWindow;
        private var myTimer1:Timer;
		
		/**
        * Inicializa o FileReference e adiciona os EventListeners 
        */
        public function UploadButton():void 
        {
            fr = new FileReference();
            fr.addEventListener(Event.SELECT, selectHandler);
            fr.addEventListener(Event.OPEN, openHandler);
            fr.addEventListener(ProgressEvent.PROGRESS, progressHandler);
            fr.addEventListener(Event.COMPLETE, completeHandler);
            
            var urlServidor:String = ObterEnderecoServidor(ServerConfig.getChannel("my-amf").endpoint);
			this.UPLOAD_URL = (urlServidor + "UploadFile.ashx");
			
			myTimer1 = new Timer(3000, 1);
			myTimer1.addEventListener(TimerEvent.TIMER_COMPLETE, timerHandler1);
        }
        
        public function ObterEnderecoServidor(enderecoCompleto:String):String
        {
        	while((enderecoCompleto.substring(enderecoCompleto.length - 1, enderecoCompleto.length) != "/"))
        	{
        		enderecoCompleto = enderecoCompleto.substring(0, enderecoCompleto.length - 1)
    		}
        	
        	return enderecoCompleto;
        }   

		public function set UrlUpload(url:String):void
		{
			this.UPLOAD_URL = url;
		}
		
		public function get UrlUpload():String
		{
			return this.UPLOAD_URL;
		}

        /**
        * Prepara o label da barra de progressão para informar o % de envio do arquivo
        */
        private function openHandler(event:Event):void 
        {
            pb.label = "Carregando %3%%";
        }

        /**
        * Atualiza o percentual concluído.
        */
        private function progressHandler(event:ProgressEvent):void
        {
            pb.setProgress(event.bytesLoaded, event.bytesTotal);
        }

        /**
         * Após o upload completo, é alterado o label da barra de progressão, informando ao usuário o fim da operação 
         */
        private function completeHandler(event:Event):void 
        {
            pb.label = "Carregamento Completo";
            myTimer1.start();
        }
        
		public function timerHandler1(event:TimerEvent):void 
		{			
            PopUpManager.removePopUp(tw);
		}
        
        /**
         * Após o arquivo selecionado o upload é executado. 
         */
        private function selectHandler(event:Event):void 
        {
            var request:URLRequest = new URLRequest();
            request.url = UPLOAD_URL;
            request.method = URLRequestMethod.POST;
            openWindow()
            fr.upload(request);
        }

		public function get Nome():String
		{
			return fr.name;
		}

        /**
         * Abre popUp com a progressBar. 
         */
        private function openWindow():void
        {
            tw = new TitleWindow();
            tw.title = "Carregando Arquivo";
            tw.width = 250;
            tw.height = 80;
            pb.percentHeight = 100;
            pb.percentWidth = 100;
            tw.addChild(pb); 
            PopUpManager.addPopUp(tw, this, true);
            tw.x = (Application.application.width - tw.width) / 2; 
            tw.y = (Application.application.height - tw.height) / 2;
        }		

        /**
        * Abre a janela para escolher o arquivo a ser feito o upload.
        */					
        override protected function clickHandler(event:MouseEvent):void 
        {
            fr.browse();
        }
    }
}